package com.ld.blecardlibrary.ble;



/**
 * Created by lirongkun on 16/9/29.
 */
public class NfcbleModel {

    public interface DataListener{
        void DataChange(byte[] data);
    }
    /**
     *
     * @param function 功能号
     * @param data 数据内容
     * @param service 服务
     */
    public void writeBytes(final int function, final byte[] data, final BluetoothLeService service) {
        writeBytes(Generate_APDU(function,data),service);
    }

    public void writeBytes(final byte[] data,final BluetoothLeService service){
        new Thread(new Runnable() {
            @Override
            public void run() {
                int length = data.length;
                for (int m = 0; m < length / 20 + 1; m++) {
                    if (m == length / 20) {
                        try {
                            byte[] bytes = new byte[length % 20];
                            System.arraycopy(data, 20 * m, bytes, 0, length % 20);
                            service.writeStringToGatt(bytes);
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        try {
                            byte[] bytes = new byte[20];
                            System.arraycopy(data, 20 * m, bytes, 0, 20);
                            service.writeStringToGatt(bytes);
                            Thread.sleep(10);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).run();
    }

    public static byte[] Generate_APDU(int function,byte[] data){
        int xor = 0;
        int len = data.length;

        int len_l = (len + 1) % 256;//低位
        int len_h = (len + 1) / 256;//高位
        byte[] cmd = new byte[len + 5];
        for (int j = 0; j < len; j++) {
            cmd[4 + j] = data[j];
        }
        cmd[0] = (byte) 0xB0;
        cmd[1] = (byte) function;
        cmd[2] = (byte) len_h;
        cmd[3] = (byte) len_l;
        for (int i = 0;i<len+4;i++){
            xor = xor^cmd[i];
        }
        cmd[len + 4] = (byte)xor;
        return cmd;
    }
}
